<template>
  <div>
    <div class="content">
      <a-form @submit="handleSubmit" style="width:70%;margin:0px auto;" :form="form">
        <a-form-item v-if="radiolist.length > 0" v-bind="formItemLayout" label="选择商户费率模板">
          <a-radio-group
            :key="item.id"
            v-for="item in radiolist"
            @change="onChange"
            v-model="radiovalue"
          >
            <a-radio :style="radioStyle" :value="item.id">
              {{item.name}}
              <!-- <a style="margin-left: 30px;" href="#">查看费率</a> -->
            </a-radio>
          </a-radio-group>
        </a-form-item>

        <div>
          <mer-rate :MerRateList="MerRateList" ref="getMerRateData"></mer-rate>
        </div>
            <!-- {
              rules: [{
              required: true, message: '请选择POS交易权限',
              }]
            }-->
        <!-- <a-form-item v-bind="formItemLayout" label="选择POS交易权限">
          <br />

          <a-checkbox-group
            v-decorator="[
          'productType',

          ]"
            @change="checkboxChange"
          >

            <a-row class="w700" :gutter="8">
              <a-col :span="4">
                <a-checkbox
                  :value="feeConfigs.posp_prelicensing ? feeConfigs.posp_prelicensing.code : ''"
                >{{ feeConfigs.posp_prelicensing ? feeConfigs.posp_prelicensing.name : '' }}</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item> -->

        <a-row>
          <a-col :xs="{ span : 24 }" :sm="{ span:12,offset:7 }">
            <div style="margin-top:30px;">
              <a-button class="submitButton" type="primary" :loading="loading" html-type="submit">下一步</a-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </div>
</template>
<script>
import { message } from "ant-design-vue";
import api from "@/common/api";
import { error } from "util";
import { fail } from "assert";
import { locale } from "moment";
import MerRate from "../../common/MerRate";
export default {
  components: {
    MerRate
  },
  data() {
    return {
      modify: {
        merchantPosp: {
          transOptions: null
        }
      },
      MerRateList:null,
      loading:false,
      transOption: [],
      selectOptions: [],
      radiolist: [],
      ratelist: [],
      options: [],
      openList: [],
      radiovalue: "",
      inputDisabled: [],
      recordData: null,
      // allDisabled: true,
      product: "",
      useApi: true,
      docking: true,
      values: null,
      memberNo: "",
      upLoadList: {},
      checkedValues: [],
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15, offset: 1 },
          md: { span: 12, offset: 1 }
        }
      },
      switchIndex: 0,
      radioStyle: {
        display: "block",
        height: "30px",
        lineHeight: "30px"
      },
      feeConfigs: {}
    };
  },
 
  beforeCreate() {
    this.form = this.$form.createForm(this);
  },
  created() {
    sessionStorage.setItem("docking", true);
    // this.getProduct();
  },
  mounted() {
    let goSpe = sessionStorage.getItem("goSpe");
    // if(goSpe == 'true'){
    //   this.feeConfigs = JSON.parse(sessionStorage.getItem("product"));
    // }else{
    //   console.log('push')
    //   this.$router.push('/userindex')
    // }
    this.getExistData();
  },
  methods: {
    
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {

          if (this.modify.merchantPosp.transOptions) {
           
            this.$refs.getMerRateData.rateConversion()

            if(this.$refs.getMerRateData.feeTemplateList.length == 0){
              console.log("数组为0")
              return false
            }
            this.$refs.getMerRateData.getTransCodeList()
            // console.log("通过",this.$refs.getMerRateData.feeTemplateList)
            let feeTemplateUpdateRequests = this.$refs.getMerRateData.feeTemplateList
            let AddMemberNofeeList = []

            feeTemplateUpdateRequests.forEach((item,index) => {
              AddMemberNofeeList[index] = {
                feeTemplate: item.feeTemplate,
                memberNo : this.memberNo,
                id: item.id
              }
            })

            let TransCodeList = this.$refs.getMerRateData.TransCodeList
            let transOption = []

            TransCodeList.forEach((item,index) => {
              if(item.open == true){
                transOption.push(item.transLimitCode)
              }
            })
            

            if (this.$route.path == "/OrgRegister/configureB/step4") {
              this.memberNo = sessionStorage.getItem("orgBMemberNo");
            } else {
              this.memberNo = sessionStorage.getItem("orgAMemberNo");
            }
            
            if(values.productType == "posp.prelicensing"){
              transOption.push(values.productType[0])
            }
            

            const updata = {
              list: AddMemberNofeeList,
              logMerchantPospUpdateRequest: {
                id: this.modify.merchantPosp.id,
                memberNo: this.memberNo,
                transOption: transOption
              }
            };
            this.loading = true;
            this.updateConfig(updata);
          }
          // ----
          // ----
          // ----
          // ----
          else {
            
            this.$refs.getMerRateData.rateConversion()

            if(this.$refs.getMerRateData.feeTemplateList.length == 0){
              console.log("数组为0")
              return false
            }
            this.$refs.getMerRateData.getTransCodeList()
            // console.log("通过",this.$refs.getMerRateData.feeTemplateList)
            let feeTemplateUpdateRequests = this.$refs.getMerRateData.feeTemplateList
            let AddMemberNofeeList = []

            feeTemplateUpdateRequests.forEach((item,index) => {
              AddMemberNofeeList[index] = {
                feeTemplate: item.feeTemplate,
                memberNo : this.memberNo,
                feeTemplateId: item.id
              }
            })

            let TransCodeList = this.$refs.getMerRateData.TransCodeList
            let transOption = []

            TransCodeList.forEach((item,index) => {
              if(item.open == true){
                transOption.push(item.transLimitCode)
              }
            })

            if (this.$route.path == "/OrgRegister/configureB/step4") {
              this.memberNo = sessionStorage.getItem("orgBMemberNo");
            } else {
              this.memberNo = sessionStorage.getItem("orgAMemberNo");
            }

            if(values.productType == "posp.prelicensing"){
              transOption.push(values.productType[0])
            }

            const data = {
              list: AddMemberNofeeList,
              logMerchantPospUpdateRequest: {
                id: this.modify.merchantPosp.id,
                memberNo: this.memberNo,
                transOption: transOption
              }
            };
            this.loading = true;
            this.addConfig(data);
          }
        }
      });
    },
    addConfig(data) {
      this.$axios.post("/agent/business/config/add", data).then(
        res => {
          console.log("res", res);
          if (res.data.code == "OK") {
            this.loading = false;
            this.$router.replace({
              path: "/OrgRegister/step5",
              query: { success: "true" }
            });
            // this.doNext(6);
          } else {
            this.loading = false;
            this.transOption = [];
            this.$message.error(res.data.message);
            // this.$router.replace({
            //   path: "/OrgRegister/step4",
            //   query: { success: "false" }
            // });
          }
        },
        err => {
          this.loading = false;
          console.log("res", res);
        }
      );
    },
    // 业务配置修改
    updateConfig(data) {
      this.$axios.post("/agent/business/config/update", data).then(
        res => {
          console.log("res", res);
          if (res.data.code == "OK") {
            this.loading = false;
            this.$router.replace({
              path: "/OrgRegister/step5",
              query: { success: "true" }
            });
            // this.doNext(6);
          } else {
             this.loading = false;
            this.transOption = [];
            this.$message.error(res.data.message);
            // this.$router.replace({
            //   path: "/OrgRegister/step4",
            //   query: { success: "false" }
            // });
          }
        },
        err => {
           this.loading = false;
          console.log("res", res);
        }
      );
    },
    getExistDataProduct() {
      let data = {};
      this.$axios.post("/agent/business/config/query/feeTemplate", data).then(
        res => {
          console.log("res", res);
          if (res.data.code == "OK") {
            this.radiolist = res.data.list;
            this.radiovalue = "";
            this.radiolist.forEach((item, index) => {
              if (item.defaultValue) {
                this.radiovalue = item.id;
                this.getratelist(this.radiovalue);
              }
            });
          }
        },
        err => {}
      );
    },
    getExistData() {
      console.log("111111111");
      if (this.$route.path == "/OrgRegister/configureB/step4") {
        this.memberNo = sessionStorage.getItem("orgBMemberNo");
      } else {
        this.memberNo = sessionStorage.getItem("orgAMemberNo");
      }

      this.$axios
        .get("/agent/merchant/network/fetch/step3/" + this.memberNo)
        .then(
          res => {
            console.log("res", res);
            if (res.data.code == "OK") {
              this.modify = res.data.data;
              this.transOption = [];
              if (this.modify.merchantPosp.transOptions) {
                this.transOption = JSON.parse(
                  this.modify.merchantPosp.transOptions
                );
                console.log(this.transOption);
                this.form.setFieldsValue({
                  productType: JSON.parse(this.modify.merchantPosp.transOptions)
                });
              }

              if (res.data.data.protocol == null || res.data.data.protocol.length == 0) {
                this.getExistDataProduct();
              } else {
                this.getfeeConfigs();
                

                let protocol =  res.data.data.protocol
                this.transOption.forEach(item => {
                    for(let idx in protocol){
                        if(item == protocol[idx][0].transLimitCode){
                          
                            protocol[idx][0].open = true
                        }

                    }

                })
                //获取已配置费率
                this.MerRateList = protocol;
                
              }
            } else {
              this.$message.error(res.data.message)
            }
          },
          err => {}
        );
    },
    getfeeConfigs() {
      let data = {};
      this.$axios.post("/agent/business/config/fetch/product", data).then(
        res => {
          if (res.data.code == "OK") {
            // 开通产品部分
            this.feeConfigs = res.data.data;
          }
        },
        err => {}
      );
    },

    doNext(step) {
      console.log(step);
      var st = step + 1;
      this.$router.push("/OrgRegister/step" + st);
    },

    checkboxChange(checkedValues) {
      console.log("checked = ", checkedValues);
      this.transOption = checkedValues;
      console.log("checked = ", this.transOption);
      
    },
    onChange(e) {
      console.log("radio checked", e.target.value);
      this.getratelist(e.target.value);
    },
    getratelist(id) {
      console.log("radio checked", id);
      this.$axios
        .get("/agent/business/config/feeTemplateDetail/" + id)
        .then(res => {
          console.log("ratelist", res);
          if (res.data.code == "OK") {
            // 开通产品部分
            this.feeConfigs = res.data.data.transOptionsResp;
            // 费率部分
            this.MerRateList =  res.data.data.feeTemplateGroupDTO.data.feeTemplateDTOMap;
          } else {
          }
        });
    }
  
  }
};
</script>
<style lang="less" scoped>
/deep/.noExpand {
  .ant-table-row-expand-icon {
    display: none;
  }
}
.content {
  /* text-align: center */
  margin: 0 auto;
}

.card {
  margin-top: 50px;
}

.card .title {
  text-align: center;
  padding: 20px;
  font-size: 18px;
}

.btn-next {
  margin-top: 20px;
}

.btn-style {
  background: #ccc;
  border: 1px solid #ccc;
  color: #eee;
}

.ant-checkbox-group .ant-checkbox-group-item {
  width: 100%;
}

.w700 {
  width: 800px;
  margin-bottom: 14px;
}

.title-sty {
  padding-right: 30px !important;
}

.submitButton {
  width: 8vw;
}
</style>